import moment from "moment";
import _ from "lodash";

// 将字节转换为 KB/MB
export const formattedSize = (size: number): string => {
  if (size < 1024) {
    return `${size} B`;
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`;
  } else {
    return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  }
};

// 将秒转换为 HH:MM:SS 格式
export function formatSeconds(seconds: any) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  const pad = (num: any) => (num < 10 ? `0${num}` : num);
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
}

// 计算宽高比
export function calculateAspectRatio(width: any, height: any) {
  function findGCD(a: any, b: any) {
    if (b === 0) {
      return a;
    }
    return findGCD(b, a % b);
  }
  const gcd = findGCD(width, height);
  return `${width / gcd}:${height / gcd}`;
}

// 发送给后端的数据与保存为模板的数据
export function getQutoutiaoSendData(data: any) {
  /**
   * 处理计划
   */
  // 日期、计划投放状态
  const Plan = _.cloneDeep(data.Plan);
  if (Plan.date && Plan.date.length) {
    Plan.start_date = moment(Plan.date[0]).format("YYYY-MM-DD");
    Plan.end_date = moment(Plan.date[1]).format("YYYY-MM-DD");
  }
  if (Plan.tomorrow_budget_state === 0) {
    delete Plan.tomorrow_budget;
  }
  delete Plan.date;

  /**
   * 处理单元
   */
  const Campaign = _.cloneDeep(data.Campaign);

  /**
   * 处理创意基本信息
   */
  const CreativeConfig = _.cloneDeep(data.CreativeConfig);
  const { appSetting } = CreativeConfig;
  if (appSetting) {
    for (let key in appSetting) {
      if (!_.isEmpty(appSetting[key])) {
        if (appSetting[key].target_url_h5) {
          if (appSetting[key].target_url_h5.indexOf("whale") === -1 && appSetting[key].target_url_h5.indexOf("chitu") === -1) {
            delete appSetting[key].target_type;
            delete appSetting[key].clk_site_id;
          } else {
            // delete appSetting[key].target_url_h5;
          }
        }
      }
    }
  }

  // 副标题
  if (CreativeConfig.second_title) {
    CreativeConfig.description = CreativeConfig.second_title;
  }

  /**
   * 处理创意
   */
  let Creatives: any = _.cloneDeep(data.Creatives);

  // 视频广告横板/竖版 激励视频横板/竖版
  if (
    CreativeConfig.type === "VIDEO_HORIZONTAL" ||
    CreativeConfig.type === "VIDEO_VERTICAL" ||
    CreativeConfig.type === "MOTIVATE_VIDEO_HORIZONTAL" ||
    CreativeConfig.type === "MOTIVATE_VIDEO_VERTICAL"
  ) {
    Creatives.forEach((creative: any) => {
      creative.Covers.forEach((cover: any) => {
        cover.CsType = cover.csType;
        cover.FileSize = cover.fileSize;
        cover.Height = cover.height;
        cover.IsOss = cover.isOss;
        cover.Md5 = cover.md5;
        cover.Name = cover.name;
        cover.Path = cover.path;
        cover.PreviewUrl = cover.previewUrl;
        cover.Thumb = cover.thumb;
        cover.Type = cover.type;
        cover.Width = cover.width;
      });

      if (creative.Materials[0]) {
        creative.Materials[0].IsMaterial = true;
      }

      if (creative.Materials[1]) {
        creative.Materials[1].CsType = creative.Materials[1].csType;
        creative.Materials[1].FileSize = creative.Materials[1].fileSize;
        creative.Materials[1].Height = creative.Materials[1].height;
        creative.Materials[1].IsOss = creative.Materials[1].isOss;
        creative.Materials[1].Md5 = creative.Materials[1].md5;
        creative.Materials[1].Name = creative.Materials[1].name;
        creative.Materials[1].Path = creative.Materials[1].path;
        creative.Materials[1].PreviewUrl = creative.Materials[1].previewUrl;
        creative.Materials[1].Thumb = creative.Materials[1].thumb;
        creative.Materials[1].Type = creative.Materials[1].type;
        creative.Materials[1].Width = creative.Materials[1].width;
        creative.Materials[1].IsCover = true;
      }
    });
  }

  let sendData = {
    AdxId: data.AdxId,
    LabelIds: [],
    AccountIds: data.AccountIds,
    Strategy: {
      NORMAL: true,
      targets_rule: "NORMAL",
      titles_rule: "NORMAL",
    },
    Plan,
    Campaign,
    TargetIds: data.TargetIds,
    TitlePackageIds: data.TitlePackageIds,
    CreativeConfig,
    Creatives,
    Monitor: data.Monitor,
  };
  return sendData;
}

export function getBaiduSendData(data: any) {
  return data;
}

// 将 mapData 转换为 {账户id: [{id: 计划id, name: 计划名称}]} 的形式
const convertToSimpleFormat = (mapData: any) => {
  const result: any = {};
  if (mapData) {
    mapData.forEach((item: any) => {
      const accountId = item.account._id;
      const selectedIds = item.data.selected || [];
      const planList = item.data.list || [];

      if (selectedIds.length > 0) {
        result[accountId] = selectedIds.map((id: any) => {
          const plan = planList.find((item: any) => item._id === id);
          return {
            id: id,
            name: plan.Name,
          };
        });
      }
    });
  }
  return result;
};

export function getQianchuanQySendData(data: any) {
  /**
   * 处理计划
   */
  const oPlan = _.cloneDeep(data.Plan);

  const Plan: any = {
    marketing_goal: oPlan.marketing_goal,
    name: oPlan.name,
    delivery_setting: {
      budget: oPlan.budget,
      smart_bid_type: "SMART_BID_CUSTOM",
      roi2_goal: oPlan.roi2_goal,
      qcpx_mode: oPlan.qcpx_mode,
      schedule_type: oPlan.schedule_type,
    },
  };
  if (oPlan.schedule_type === "SCHEDULE_START_END") {
    Plan.delivery_setting.start_time = oPlan.start_time;
    Plan.delivery_setting.end_time = oPlan.end_time;
  }

  Plan.campaign_map = convertToSimpleFormat(oPlan.select_plans);

  // 处理创意
  const Creatives = _.cloneDeep(data.Creatives);

  // 发送的数据
  const sendCreatives: any = [];

  for (let i = 0; i < Creatives.length; i++) {
    const creative = Creatives[i];

    const creativeSend: any = {
      Materials: [],
      SubmitData: {
        campaigns: [],
        products: [],
      },
    };

    creativeSend.SubmitData.campaigns = creative.planIds;
    creativeSend.SubmitData.products = creative.productIds;

    creative.videoMaterials.forEach((item: any) => {
      creativeSend.Materials.push(item);
      creativeSend.Materials.push(item.Cover);
    });

    creative.imageMaterials?.forEach((item: any) => {
      creativeSend.Materials.push(item);
    });

    sendCreatives.push(creativeSend);
  }

  let sendData = {
    AdxId: data.AdxId,
    AdxSubId: data.AdxSubId,
    LabelIds: [],
    AccountIds: data.AccountIds,
    Strategy: {},
    Plan,
    Campaign: {},
    TargetIds: [],
    TitlePackageIds: data.TitlePackageIds,
    CardTitlePackageIds: data.CardTitlePackageIds,
    Creatives: sendCreatives,
  };

  return sendData;
}

interface FormatTimeParams {
  target: "arr" | "obj";
  arr?: number[];
  obj?: Record<string, number[]>;
}
// 趣头条，转换时间段格式
export const formatTimeQutoutiao = ({ target, arr = [], obj = {} }: FormatTimeParams): number[] | Record<number, number[]> => {
  // 转换对象到数组
  if (target === "arr") {
    return Object.values(obj).map((bits) => bits.reduce((num, bit, index) => num + (bit === 1 ? Math.pow(2, index) : 0), 0));
  }

  // 转换数组到对象
  if (target === "obj") {
    const BITS_LENGTH = 24;
    return arr.reduce((result, num, index) => {
      result[index + 1] = Array.from({ length: BITS_LENGTH }, (_, i) => (num & (1 << i) ? 1 : 0));
      return result;
    }, {} as Record<number, number[]>);
  }

  throw new Error("Invalid target parameter");
};

/**
 * 小米：将城市数据转换为树结构，直辖市直接放在第一层
 * @param {Array} data 原始城市数据
 * @return {Array} 树形结构数据
 */
export const convertToTree = (data: any) => {
  // 计算每个省份下的城市数量
  const provinceCounts:any = {};
  data.forEach((item:any) => {
    if (!provinceCounts[item.desc]) {
      provinceCounts[item.desc] = 0;
    }
    provinceCounts[item.desc]++;
  });

  // 结果数组
  const result:any = [];

  // 按省份分组的临时对象
  const provinceMap:any = {};

  // 遍历原始数据
  data.forEach((item:any) => {
    // 如果该省份只有一个城市且名称与省份相同（直辖市情况）
    if (provinceCounts[item.desc] === 1 && item.name === item.desc) {
      // 直接添加到结果数组，不需要子节点
      result.push({
        label: item.desc,
        value: item.key,
        isLeaf: true,
      });
    } else {
      // 常规省份处理
      if (!provinceMap[item.desc]) {
        provinceMap[item.desc] = {
          label: item.desc,
          value: item.desc,
          children: [],
        };
        // 添加到结果数组
        result.push(provinceMap[item.desc]);
      }

      // 将城市添加到对应省份的children中
      provinceMap[item.desc].children.push({
        label: item.name,
        value: item.key,
        isLeaf: true,
      });
    }
  });

  return result;
}